/**
 * desc：
 * author：王文军
 * date：  2022/4/7 21:25
 */
"use strict";

const { createCloudBuildTask } = require("../../models/CloudBuildTask");
const { getTokenValue } = require("../../utils");
const { verify } = require("jsonwebtoken");

const REDIS_PREFIX = "cloudbuild";

module.exports = (options) => {
  return async (ctx, next) => {
    const { app, socket, logger, helper } = ctx;
    const { id } = socket;
    const { redis } = app;
    const query = socket.handshake.query;
    // START auth认证
    const authorization = socket.handshake.headers.authorization;
    const { secret } = options.config.jwt;
    const token = getTokenValue(authorization);
    try {
      if (!authorization || typeof authorization !== "string" || !token) {
        socket.client.disconnect();
        return;
      }
      const res = verify(token, secret);
    } catch (e) {
      console.log(">>>>>>> auth error", e);
      socket.client.disconnect();
      return;
    }
    // END auth认证
    try {
      socket.emit(
        id,
        helper.parseMsg("connect", {
          type: "connect",
          message: "云构建服务连接成功",
        })
      );
      let hasTask = await redis.get(`${REDIS_PREFIX}:${id}`);
      if (!hasTask) {
        await redis.set(`${REDIS_PREFIX}:${id}`, JSON.stringify(query));
      }
      hasTask = await redis.get(`${REDIS_PREFIX}:${id}`);
      console.log("???????????", hasTask);
      logger.info("query", hasTask);
      await next();
      // 清除缓存文件
      const cloudBuildTask = await createCloudBuildTask(ctx, app);
      await cloudBuildTask.clean();
      console.log("disconnect!");
    } catch (e) {
      logger.error("build error", e.message);
      // 清除缓存文件
      const cloudBuildTask = await createCloudBuildTask(ctx, app);
      await cloudBuildTask.clean();
    }
  };
};
